#include "StdAfx.h"
#include "LandArea.h"
#include <osgSim/ShapeAttribute>

LandArea::LandArea(void)
{
}

LandArea::~LandArea(void)
{
}

Node* LandArea::loadLandArea(const string& s57file,
							 const string& shpDir,
							 const GisColor& landColor,
							 Group* labelGroup,
							 LabelMode labelMode, 
							 map<string, string>& dictionary)
{
	string shpFile(shpDir);
	shpFile.append("/LNDARE.shp");

	float r, g, b, a;
	r = landColor.r / 255.0f;
	g = landColor.g / 255.0f;
	b = landColor.b / 255.0f;
	a = landColor.a / 255.0f;

	Node* node = loadShpFileAndSetColor(shpFile, r, g, b, a);
	if (!node)
	{
		char** cmd = new char*[7];
		cmd[0] = "ogr2ogr";
		cmd[1] = "-skipfailure";
		cmd[2] = new char[100];
		cmd[3] = new char[100];
		cmd[4] = "-nlt";
		cmd[5] = "polygon";
		cmd[6] = "LNDARE";
		sprintf(cmd[2], shpDir.c_str());
		sprintf(cmd[3], s57file.c_str());

		ogr2ogr(7, cmd);

		delete [] cmd[2];
		delete [] cmd[3];
		delete [] cmd;

		node = loadShpFileAndSetColor(shpFile, r, g, b, a);
	}
	if (!node)
	{
		return NULL;
	}

	loadLabels(static_cast<Geode*>(node), labelGroup, labelMode, dictionary);
	return node;
}

void LandArea::loadLabels(Geode* geode, Group* labelGroup, LabelMode labelMode, map<string, string>& dictionary)
{
	const Geode::DrawableList& drawableList = geode->getDrawableList();
	Geode::DrawableList::const_iterator it = drawableList.begin();
	for (; it != drawableList.end(); ++it)
	{
		Geometry* geom = static_cast<Geometry*>(it->get());

		osgSim::ShapeAttributeList* attrList = static_cast<osgSim::ShapeAttributeList*>(geom->getUserData());
		osgSim::ShapeAttribute OBJNAM = (*attrList)[11];
		string name = OBJNAM.getName();
		string val = OBJNAM.getString();
		int spacePos = val.find_last_not_of(' ');
		val.erase(spacePos+1);
		if (name == "OBJNAM" && val != "")
		{
			if (dictionary.find(val) == dictionary.end())
			{
				if (labelMode == ONLY_SHOW_CHINESE_LABELS)
				{
					continue;
				}
			}
			else
			{
				val = dictionary[val];
			}

			const BoundingBox& box = geom->getBound();
			double x, y;
			x = (box.xMin() + box.xMax()) * 0.5;
			y = (box.yMin() + box.yMax()) * 0.5; 

			Label* label = new Label(val, 22, x, y, 0, 1.0, 1.0, 1.0, TextBase::LEFT_CENTER);
			labelGroup->addChild(label);
		}

	}
}
